var className = document.getElementById('classname').innerHTML;
var tas = document.getElementsByClassName(className);
var data_to_send = [];
var last_saved_values = [];
var cms = [];
var isStudent = document.getElementById('student').innerHTML;

var url = '/interview/api/interviews/'

function checkChanged() {
    for (var i=0, l=cms.length; i<l; i++) {
        if(last_saved_values[i] !== cms[i].getValue()) {
            var form = cms[i].getWrapperElement().parentNode;
            $(form).find('label.hint').text('changed');
            // console.log($(form).find('label.hint').text());
        }
    }
}

function sendInput() {
    for (var i=0, l=cms.length; i<l; i++) {
        if(last_saved_values[i] !== cms[i].getValue()) {
            var form = cms[i].getWrapperElement().parentNode;
            var lbl = $(form).find('label.hint');
            var content = cms[i].getValue();
            var interview_id= $(form).find('div#interview_id').html();
            var data = {
                  answer: content,
              };
            console.log(data);
            $.ajax({
              url: url + interview_id + '/',
              method: 'PATCH',
              data: data,
              context: {
                lbl: lbl,
                content: content,
                i: i,
              },
              success: function( result , textStatus) {
                console.log(result, url);
                last_saved_values[this.i] = this.content;
                if (textStatus == 'success'){
                    this.lbl.text('saved');
                }else{
                    this.lbl.text('cannot update now');
                }
              }
            });
        }
    }
}

function onChange(cm, change) {
    // console.log(change);
    // console.log(cm.getInputField());
    // console.log(cm.getValue());
    // var form = cm.getWrapperElement().parentNode;
    // $(form).find('label.hint').text('changed');
}

for (var i=0, l=tas.length; i<l; i++) {
    tas[i].id = 'ta-' + i;
    last_saved_values.push(tas[i].value)
    var cm = CodeMirror.fromTextArea(tas[i]);
    cm.on("change", onChange);
    cms.push(cm);
    // break;
}

var CHECK_INTERVAL = 500;
setInterval(checkChanged, CHECK_INTERVAL);
var SEND_INTERVAL = 3000;
setInterval(sendInput, SEND_INTERVAL);
